<?php

namespace Beerus\Modules\DesignerCompetition2020\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Doraemon\model\Article;
use Doraemon\model\ArticleHouse;
use Doraemon\model\DesignerCompetition\DesignerAwardSign2020;
use Doraemon\model\DesignerCompetition\FinalReview;
use Doraemon\model\DesignerCompetition\NavigatorScore;
use Doraemon\model\DesignerCompetition\Confirmation;
use Doraemon\model\Member;
use Doraemon\service\DesignerCompetition2020\ReviewService;
use Doraemon\service\DesignerCompetition2020\SignService;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;

/**
 * 初筛确认
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */

class FinalVerifyController extends Controller
{
    const PAGE_SIZE = 10;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    /**
     * 终筛确认
     * @param Request $request
     * @param Content $content
     * @param int $tab_id
     * @return Content
     */
    public function index(Request $request, Content $content, $tab_id = 1)
    {
        $request_params = $request->all();

        $page_size = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);

        $condition = $this->condition($request_params, $tab_id);

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $tab = new Tab();
        $tab->addLink('终筛确认（户型）', '/admin/DesignerCompetition2020/verify/final/1', $tab_id == 1);
        $tab->addLink('终筛确认（软装）', '/admin/DesignerCompetition2020/verify/final/2', $tab_id == 2);
        $tab->addLink('终筛确认（平面）', '/admin/DesignerCompetition2020/verify/final/3', $tab_id == 3);

        return $content
            ->header('终筛确认')
            ->breadcrumb(
                ['text' => '终筛确认', 'url' => '/admin/DesignerCompetition2020/verify/final/'. $tab_id]
            )
            ->body($tab)
            ->row(self::indexGrid($condition, $tab_id));
    }

    /**
     * 表格展示部分
     * @param $condition
     * @param $tab_id
     * @return Grid
     */
    public function indexGrid($condition, $tab_id)
    {
        Admin::script($this->jumpScript());

        $lists = DesignerAwardSign2020::select('*', $condition);

        unset($condition['ORDER']);
        unset($condition['LIMIT']);
        $total = DesignerAwardSign2020::count('*', $condition);

        if (!empty($lists)) {
            $user_ids = array_column($lists, 'uid');
            $member_info = Member::getUsers($user_ids);

            foreach ($lists as &$item) {
                // 用户信息
                $item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
                $item['user_type'] = SignService::USER_TYPE[$member_info[$item['uid']]['type']];

                // 参赛信息
                $item['from_name'] = SignService::FROM[$item['channel']];
                $item['area_text'] = SignService::AREA[$item['area']];
                $item['house_model'] = SignService::HOUSE_MODEL[$item['house_model']];

                $item['is_plane'] = $item['is_soft'] = '否';
                if ($item['award_type'] == DesignerAwardSign2020::DESIGNER_BEST_PLANE_AWARD) {
                    $item['is_plane'] = '是';
                } elseif ($item['award_type'] == DesignerAwardSign2020::DESIGNER_BEST_SOFT_AWARD) {
                    $item['is_soft'] = '是';
                } elseif ($item['award_type'] == DesignerAwardSign2020::DESIGNER_BEST_PLANE_SOFT_AWARD) {
                    $item['is_plane'] = $item['is_soft'] = '是';
                }

                $item['sign_time'] = date('Y-m-d H:i:s', $item['add_time']);

                // 作品链接
                if ($item['channel'] == DesignerAwardSign2020::FROM_OWNER) {
                    $article_info = Article::getArticle($item['article_id']);
                    $item['work_name'] = empty($article_info) ? '作品名称无' : $article_info['title'];
                    $item['link'] = Hhzurl::getDomain(). "/bangyang/{$item['article_id']}.html";
                    $item['work_pic_url'] = ImgUrl::getUrl(
                        ImgUrl::APPTYPE_APP,
                        $article_info['cover_pic_id'],
                        ImgUrl::IMAGE_SIZE_SQ_PHONE
                    );
                    // 初筛分数
                    $item['score'] = '';
                } elseif ($item['channel'] == DesignerAwardSign2020::FROM_DESIGNER) {
                    $live_photos = json_decode($item['live_photos'], true);
                    $item['live_photos'] = $live_photos;
                    $work_pic_url = ImgUrl::getUrl(
                        ImgUrl::APPTYPE_APP,
                        $live_photos[0]['pic_id'],
                        ImgUrl::IMAGE_SIZE_SQ_PHONE
                    );
                    $item['work_pic_url'] = $work_pic_url; // 取实景作品的第一条

                    $item['link'] = Hhzurl::getDomain(). "/designer/game/2020/production-detail?id={$item['id']}";

                    // 获取当前参赛作品所在赛区的领航员
                    $navigators = ReviewService::REVIEWER[$item['area']];
                    // 查询用户nick
                    $navigators_info = Member::getUsers($navigators);

                    $score_info = [];
                    foreach ($navigators as $navigator) {
                        $nick = empty($navigators_info[$navigator]['nick']) ?
                            '未知用户' : $navigators_info[$navigator]['nick'];
                        $condition = [
                            'sign_id' => $item['id'],
                            'uid' => $navigator,
                        ];
                        $review_record = NavigatorScore::getByCondition($condition);

                        if (empty($review_record)) {
                            $score_info[] = "{$nick}：未打分";
                        } else {
                            if ($tab_id == ReviewService::AWARD_HOUSE) {
                                if (empty($review_record['house_score'])) {
                                    $score_info[] = "{$nick}：未打分";
                                } else {
                                    $score = (int)$review_record['house_score'];

                                    if ($score == 3) {
                                        $score_info[] = "{$nick}：<b style='color: red'>{$score}分</b>";
                                    } else {
                                        $score_info[] = "{$nick}：{$score}分";
                                    }
                                }
                            } elseif ($tab_id == ReviewService::AWARD_PLANE) {
                                if (empty($review_record['plane_score'])) {
                                    $score_info[] = "{$nick}：未打分";
                                } else {
                                    $score = (int)$review_record['plane_score'];

                                    if ($score == 3) {
                                        $score_info[] = "{$nick}：<b style='color: red'>{$score}分</b>";
                                    } else {
                                        $score_info[] = "{$nick}：{$score}分";
                                    }
                                }
                            } elseif ($tab_id == ReviewService::AWARD_SOFT) {
                                if (empty($review_record['soft_score'])) {
                                    $score_info[] = "{$nick}：未打分";
                                } else {
                                    $score = (int)$review_record['soft_score'];

                                    if ($score == 3) {
                                        $score_info[] = "{$nick}：<b style='color: red'>{$score}分</b>";
                                    } else {
                                        $score_info[] = "{$nick}：{$score}分";
                                    }
                                }
                            }
                        }
                    }

                    $total_score = 0;
                    if ($tab_id == ReviewService::AWARD_HOUSE) {
                        $total_score = $item['house_score'];
                        $item['final_audit'] = $item['final_house_audit'];
                    } elseif ($tab_id == ReviewService::AWARD_PLANE) {
                        $total_score = $item['plane_score'];
                        $item['final_audit'] = $item['final_plane_audit'];
                    } elseif ($tab_id == ReviewService::AWARD_SOFT) {
                        $total_score = $item['soft_score'];
                        $item['final_audit'] = $item['final_soft_audit'];
                    }

                    $score_info[] = "<b style='color: blue'>总分：". $total_score . "分</b>";
                    $item['score_info'] = implode('<br/>', $score_info);

                    // 获取当前参赛作品所在赛区终筛评审员
                    $judge = ReviewService::JUDGE[$item['area']];
                    // 查询用户nick
                    $judge_info = Member::getUsers($judge);

                    $review_record = FinalReview::listByCondition([
                        'sign_id' => $item['id'],
                        'award_type' => $tab_id
                    ]);
                    $map_review = [];
                    if (!empty($review_record)) {
                        foreach ($review_record as $review_item) {
                            $map_review[$review_item['sign_id'] . $review_item['uid']. $tab_id] = $review_item;
                        }
                    }

                    $vote_info = [];
                    foreach ($judge as $judge_item) {
                        $nick = empty($judge_info[$judge_item]['nick']) ?
                            '未知用户' : $judge_info[$judge_item]['nick'];
                        $flag = $item['id'] . $judge_item. $tab_id;
                        if (empty($map_review[$flag])) {
                            $vote_info[] = "{$nick}：未打分";
                        } else {
                            $audit_result = ReviewService::AUDIT_STATUS_MAP[$map_review[$flag]['audit_status']];
                            $vote_info[] = "{$nick}：{$audit_result}";
                        }
                    }

                    if ($tab_id == ReviewService::AWARD_HOUSE) {
                        $vote_info[] = "<b style='color: blue'>总票数：" . $item['house_vote'] . "</b>";
                    } elseif ($tab_id == ReviewService::AWARD_SOFT) {
                        $vote_info[] = "<b style='color: blue'>总票数：" . $item['soft_vote'] . "</b>";
                    } elseif ($tab_id == ReviewService::AWARD_PLANE) {
                        $vote_info[] = "<b style='color: blue'>总票数：" . $item['plane_vote'] . "</b>";
                    }

                    $item['vote_info'] = implode('<br/>', $vote_info);
                }

                // 作品信息
                $article_house = ArticleHouse::getArticleHouseById($item['article_id']);

                $item['house_construction'] = $item['house_stuff'] =  $item['house_area'] = '';
                if (!empty($article_house)) {
                    // 户型
                    $house_arr = explode(',', $article_house['house_construction']);
                    $item['house_construction'] = $house_arr[0] . '室';
                    // 房屋所在地
//                    $house_area_ids = explode(',', $article_house['area']);
//                    $area = implode(' ', array_map(function ($area_id) {
//                        return Area::locationId2location($area_id);
//                    }, $house_area_ids));
//                    $item['house_area'] = $area;
                    $item['house_area'] = $article_house['area_name'];
                }

                // 常住人口
                if ($item['people'] == 5) {
                    $people = $item['other_people'];
                } else {
                    $people = DesignerAwardSign2020::PEOPLE[$item['people']];
                }
                $item['people'] = $people;
            }
            unset($item);
        }

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => self::PAGE_SIZE
        ]);

        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function ($filter) {
                        // 用户身份
                        $filter->equal('user_type', '用户身份')->select(SignService::USER_TYPE_MAP);
                        // 赛区
                        $filter->equal('area', '赛区')->select(SignService::AREA);
                        // 户型
                        $filter->equal('house_model', '户型')->select(SignService::HOUSE_MODEL);
                        // 评审结果
                        $filter->equal('final_audit', '评审结果')->select(ReviewService::AUDIT_STATUS_MAP);
                    });

                    $filter->column(1 / 2, function ($filter) {
                        $options = ['-1' => '全部', '1' => '是', '2' => '否'];
                        $filter->equal('is_remark', '包含备注')->radio($options)->default('-1');
                        $filter->equal('remark', '备注内容');
                        $filter->equal('uid', '用户uid');
                        $filter->equal('vote', '评委总票数');
                    });
                    $filter->expand();
                });

                $grid->column('id', '报名id')->width(70);
                $grid->column('user_info', '用户信息')->width(140)->display(function () {
                    $userInfo[] = 'uid：' . $this->uid;
                    $userInfo[] = '昵称：<a class="jump_user" href="javascript:void(0);"> ' . $this->nick . '</a>';
                    $userInfo[] = '身份：' . $this->user_type;
                    return implode('<br/>', $userInfo);
                });

                $grid->column('competition_info', '参赛信息')->width(240)->display(function () {
                    if ($this->channel == DesignerAwardSign2020::FROM_OWNER) {
                        $competition_info[] = '通道：'. $this->from_name;
                        $competition_info[] = '报名时间：'. $this->sign_time;

                        return implode('<br/>', $competition_info);
                    } elseif ($this->channel == DesignerAwardSign2020::FROM_DESIGNER) {
                        $competition_info[] = '通道：'. $this->from_name;
                        $competition_info[] = '赛区：'. $this->area_text;
                        $competition_info[] = '户型：'. $this->house_model;
                        $competition_info[] = '软装：'. $this->is_soft;
                        $competition_info[] = '平面：'. $this->is_plane;
                        $competition_info[] = '报名时间：'. $this->sign_time;

                        return implode('<br/>', $competition_info);
                    } else {
                        return '报名入口来源未知';
                    }
                });

                $grid->column('work_link', '作品链接')->width(210)->display(function () {
                    $open = isset($this->work_name) ? '<a class="fa " href="javascript:layer.open({type: 2, 
                    title: \'预览\', maxmin: true, area: [\'650px\', \'700px\'], 
                    content: \'' . $this->link . '\' });">' . htmlentities($this->work_name) . '</a>' : "";
                    $img = "<img width='200' height='200' src='{$this->work_pic_url}'>";
                    return implode('<br/>', [$img, $open]);
                });

                $grid->column('work_info', '作品信息')->width(400)->display(function () {
                    $work_info = [];
                    if ($this->channel == DesignerAwardSign2020::FROM_OWNER) {
                        return '无';
                    } elseif ($this->channel == DesignerAwardSign2020::FROM_DESIGNER) {
                        $work_info[] = '户型：'. $this->house_construction;
                        $work_info[] = '总造价：'. $this->total_price .'万元';
                        $work_info[] = '地区：'. $this->house_area;
                        $work_info[] = '常住人口：'. $this->people;
                        $work_info[] = '项目完成时间：'. $this->design_finish_date;
                        $work_info[] = '满意的产品：'. $this->most_satisfied;
                        $work_info[] = '产品品牌：'. $this->satisfied_brand;
                        $work_info[] = '满意的原因：'. $this->satisfied_reason;

                        return implode('<br/>', $work_info);
                    } else {
                        return '报名入口来源未知';
                    }
                });

                $grid->column('score_info', '初筛分数')->width(240)->display(function () {
                    if ($this->channel == DesignerAwardSign2020::FROM_OWNER) {
                        return $this->score_info;
                    } elseif ($this->channel == DesignerAwardSign2020::FROM_DESIGNER) {
                        return $this->score_info;
                    } else {
                        return '报名入口来源未知';
                    }
                });

                $grid->column('vote_info', '终筛分数')->width(240)->display(function () {
                    return $this->vote_info;
                });

                $grid->column('final_audit', '评审结果')->width(100)->radio(ReviewService::AUDIT_STATUS_MAP);

                $grid->column('remark', '备注')->width(200)->editable();

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                });
                $grid->disableActions();
            }
        );

        return $gridList;
    }

    private function condition($request, $tab)
    {
        $response = [
            'audit_status' => DesignerAwardSign2020::AUDIT_STATUS_CONFIRM,
            'channel' => DesignerAwardSign2020::FROM_DESIGNER
        ];

        if ($tab == ReviewService::AWARD_PLANE) {
            $response['award_type'] = [
                DesignerAwardSign2020::DESIGNER_BEST_PLANE_AWARD,
                DesignerAwardSign2020::DESIGNER_BEST_PLANE_SOFT_AWARD];
        } elseif ($tab == ReviewService::AWARD_SOFT) {
            $response['award_type'] = [
                DesignerAwardSign2020::DESIGNER_BEST_SOFT_AWARD,
                DesignerAwardSign2020::DESIGNER_BEST_PLANE_SOFT_AWARD];
        }

        // 用户uid
        if (!empty($request['uid'])) {
            $response['uid'] = $request['uid'];
        }

        // 用户身份
        if (!empty($request['user_type'])) {
            $response['user_type'] = $request['user_type'];
        }

        // 赛区
        if (!empty($request['area'])) {
            $response['area'] = $request['area'];
        }

        // 户型
        if (!empty($request['house_model'])) {
            $response['house_model'] = $request['house_model'];
        }

        // 评审结果
        if (!empty($request['final_audit']) && ($request['final_audit'] !== 0)) {
            if ($tab == ReviewService::AWARD_HOUSE) {
                $response['final_house_audit'] = $request['final_audit'];
            } elseif ($tab == ReviewService::AWARD_SOFT) {
                $response['final_soft_audit'] = $request['final_audit'];
            } elseif ($tab == ReviewService::AWARD_PLANE) {
                $response['final_plane_audit'] = $request['final_audit'];
            }
        }

        // 备注
        if (!empty($request['is_remark'])) {
            if ($request['is_remark'] == 1) {
                // 备注匹配
                if (isset($request['remark']) && ($request['remark'] !== '')) {
                    $response['remark[~]'] = $request['remark'];
                } else {
                    $response['remark[!]'] = '';
                }
            } elseif ($request['is_remark'] == 2) {
                // 备注匹配
                if (isset($request['remark']) && ($request['remark'] !== '')) {
                    $response['id'] = 0;
                } else {
                    $response['remark'] = '';
                }
            }
        }

        // 备注匹配
        if (isset($request['remark']) && ($request['remark'] !== '')) {
            $response['remark[~]'] = $request['remark'];
        }

        // 评委总票数
        if (!empty($request['vote'])) {
            if ($tab == ReviewService::AWARD_HOUSE) {
                $response['house_vote'] = explode(',', $request['vote']);
            } elseif ($tab == ReviewService::AWARD_SOFT) {
                $response['soft_vote'] = explode(',', $request['vote']);
            } elseif ($tab == ReviewService::AWARD_PLANE) {
                $response['plane_vote'] = explode(',', $request['vote']);
            }
        }

        return $response;
    }

    private function jumpScript()
    {
        return <<<SCRIPT
        // 用户详情跳转
        $('.jump_user').unbind('click').click(function(){
            let win = window.open('http://manage.haohaozhu.me/','用户详情','name=用户详情');
            win.openapp('/User/Oauthadmin/detail/uid/608209','user_detail608209','用户详情');
        });
        
        $('.btn-xs').hide();
        
        $("input[name='grid-radio-final_audit']").change(
		function() {
		        id = $(this).parents('.grid-radio-final_audit')[0].getAttribute('data-key');
                var final_audit = $(this).val();
                
                var tab = 1;
                if (window.location.href.indexOf("?") != -1) {
                    tab = window.location.href.split('?')[0].split('/').pop();
                } else {
                    tab = window.location.href.split('/').pop();
                }
                
                $.ajax({
                    url: '/admin/DesignerCompetition2020/verify/final/audit/' + id,
                    type: "POST",
                    data: {_method:"PUT", final_audit: final_audit, tab_id: tab},
                    dataType:"json",
                    success:function(result){
                        if (result.status) {
                            toastr.success(result.message);
                        } else {
                            toastr.warning(result.message);
                        }
                    },
                    error:function(){
                        toastr.error('系统错误,请联系管理员');
                    }
                });
	    });
SCRIPT;
    }

    public function review(Request $request, $id)
    {
        $pjax = true;
        $status = true;
        $begin_audit = $request->input('final_audit');
        $award_type = $request->input('tab_id');

        $message = "修改成功";
        try {
            $sign_info = DesignerAwardSign2020::getById($id);
            if (isset($begin_audit)) {
                if ($award_type == ReviewService::AWARD_HOUSE) {
                    DesignerAwardSign2020::update(['final_house_audit' => $begin_audit], ['id' => $id]);
                } elseif ($award_type == ReviewService::AWARD_SOFT) {
                    DesignerAwardSign2020::update(['final_soft_audit' => $begin_audit], ['id' => $id]);
                } elseif ($award_type == ReviewService::AWARD_PLANE) {
                    DesignerAwardSign2020::update(['final_plane_audit' => $begin_audit], ['id' => $id]);
                }

                $condition = [
                    'sign_id' => $id,
                    'award_type' => $award_type,
                    'stage' => Confirmation::STAGE_FINAL
                ];
                $result = Confirmation::getByCondition($condition);

                $data = [
                    'area' => $sign_info['area'],
                    'house_model' => $sign_info['house_model'],
                    'award_type' => $award_type,
                    'audit_status' => $begin_audit,
                    'admin_id' => Admin::user()->id,
                    'stage' => Confirmation::STAGE_FINAL
                ];

                if (empty($result)) {
                    // 记录初筛确认结果
                    $data['sign_id'] = $id;
                    $data['add_time'] = time();

                    Confirmation::create($data);
                } else {
                    $data['edit_time'] = time();
                    Confirmation::update($data, $condition);
                }
            } else {
                throw new \Exception('缺少参数错误');
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();

            if (!$pjax) {
                return response()->json(['errors' => [$message]], 422);
            }
        }

        return response()->json(compact('message', 'status'));
    }

    public function remark(Request $request, $tab, $id)
    {
        $pjax = true;
        $status = true;
        $name = $request->input('name');
        $value = $request->input('value');

        $message = "修改成功";
        try {
            if (isset($name) && isset($value)) {
                switch ($name) {
                    case 'remark':
                        $pjax = false;
                        if (mb_strlen($value) > 300) {
                            throw new \Exception('最多300字');
                        }
                        DesignerAwardSign2020::update(['remark' => $value], ['id' => $id]);
                        $result = Confirmation::getByCondition([
                            'award_type' => $tab,
                            'sign_id' => $id,
                            'stage' => Confirmation::STAGE_FINAL
                        ]);
                        $sign_info = DesignerAwardSign2020::getById($id);

                        if (empty($result)) {
                            Confirmation::create([
                                'sign_id' => $id,
                                'stage' => Confirmation::STAGE_FINAL,
                                'area' => $sign_info['area'],
                                'house_model' => $sign_info['house_model'],
                                'award_type' => $tab,
                                'remark' => $value,
                                'add_time' => time(),
                                'admin_id' => Admin::user()->id
                            ]);
                        } else {
                            Confirmation::update([
                                'remark' => $value,
                                'edit_time' => time(),
                                'admin_id' => Admin::user()->id
                            ], [
                                'sign_id' => $id,
                                'award_type' => $tab,
                                'stage' => Confirmation::STAGE_FINAL
                            ]);
                        }
                        break;
                    default:
                        throw new \Exception('未开发功能');
                        break;
                }
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();

            if (!$pjax) {
                return response()->json(['errors' => [$message]], 422);
            }
        }

        return response()->json(compact('message', 'status'));
    }
}
